import { defineStore, storeToRefs } from "pinia";
import { h, ref, type Component } from "vue";
import  {useEditorStore} from '@/stores/editStore'
import api from "@/api";
import { clearEditorHistory } from '@/utils/tiptap/clearHistory';
export const currentNodeInfo = defineStore(
    "currentNode",()=>{
     const isUpdate = ref(false) //当前状态是否更新古   
     const nodeId = ref()
     const title = ref()   
     const nodeMarkdown = ref() 
     const nodehtml = ref()
     const nodeText = ref()
     const stage = ref()
     const classId =ref()
     
    const updateCurrentEditorState = (data:any)=>{
        const editorStorage  = useEditorStore()
        const {editorInstance} = storeToRefs(editorStorage)
        stage.value = data.stage
        title.value = data.title
        nodeId.value = data.nodeId
        classId.value = data.classId
        editorInstance.value.commands.setContent(data.content)
        nodeText.value   = editorInstance.value.getText()
        nodehtml.value   = editorInstance.value.getHTML()
        nodeMarkdown.value = editorInstance.value.storage.markdown.getMarkdown()
        console.log("修改",data);
        
    }
   const save = () => {
      const editorStorage  = useEditorStore()
      const {editorInstance} = storeToRefs(editorStorage)
       console.log("view",editorInstance.value.view)
      clearEditorHistory(editorInstance.value.view)
      console.log("点击了保存")
      const updateInfo= {
        nodeId:nodeId.value,
        content:nodehtml.value,
        title: title.value,
        stage:stage.value,
        classId:classId.value
      }
      console.log("修改信息：",updateInfo);
      
      //先判断是否更新过
      if(isUpdate.value){
       api.nodeInfo.updateNodeById(updateInfo)
       .then((res:any)=>{
         if(res.code){
             isUpdate.value = false
             console.log( "修改成功",isUpdate.value)
         }
       }).catch((error:any)=>{
           console.log(error)
           alert("保存失败")
       })
      }else{
          
      }
       
    };

   const saveMark = () => {
       console.log("save student mark")
       
    };
    
   const reset = () => {
    console.log("重置")
     isUpdate.value = false
     nodeId.value =""
     title.value = ""
     nodeMarkdown.value =  ""
     nodehtml.value = ""
     nodeText.value = ""
    }; 

     return{
        nodeId,
        title,
        nodeMarkdown,
        nodehtml,
        nodeText,
        isUpdate,
        updateCurrentEditorState,
        save,
        reset,
        saveMark
     }
    },
      {
    persist: {
      key: "currentNodeStorage", // 自定义 localStorage 的 key
      storage: localStorage, // 明确指定使用 localStorage（默认就是它）
      paths: [
        // 明确指定要持久化的字段（可选，不设置则默认全部）
        "title",
        "nodeId",
        "isUpdate",
        "nodehtml",
        "nodeMarkdown",
        "nodeText"
        // "editorContent",
      ],

    } as any,
  }
)
